package com.testdemo.common.utils;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import com.testdemo.MyApplication;
import com.testdemo.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.RoundingMode;

/**
 * Created by dell on 2017/12/4.
 */

/**
 * //********************    图片音频等文件的公共工具类   ******************
 * //
 * //       将bitmap保存到本地（默认地址,默认自动设置图片名字）   {@link #saveBitmapToSdCard(Bitmap bitmap)}
 * //
 * //       将bitmap保存到本地（默认地址,指定图片名字）   {@link #saveBitmapToSdCard(Bitmap bitmap, String fileName)}
 * //
 * //       将bitmap保存到本地指定路径    {@link #saveBitmapToSdCard(Bitmap bitmap, String dirPath, String fileName)}
 * //
 * //       file复制到指定路径     {@link #copyFileTo(File oldFile, String newPath)}
 * //
 * //       file移动到指定路径     {@link #moveFileTo(File oldFile, String newPath)}
 * //
 * //       在限定的尺寸内读取bitmap     {@link #getBitmapByMaxSize(String path, int maxSize)}
 * //
 * //
 */

public class FileUtil {

    /**
     * 在sd卡中以项目包名命名的文件夹路径
     */
    public static final String BASE_PATH = PathGetter.getBasePath();
    /**
     * 图片存放文件夹路径
     */
    public static final String IMAGES_DIR_PATH = PathGetter.getImagesPath();
    /**
     * 普通存放文件夹路径
     */
    public static final String FILES_DIR_PATH = PathGetter.getFilesPath();
    /**
     * 音频存放文件夹路径
     */
    public static final String VOICES_DIR_PATH = PathGetter.getVoicesPath();
    /**
     * 视频存放文件夹路径
     */
    public static final String VIDEOS_DIR_PATH = PathGetter.getVideosPath();


    /**
     * 将bitmap保存到本地（默认地址,默认自动设置图片名字）
     *
     * @param bitmap
     * @return 图片全路径
     */
    public static String saveBitmapToSdCard(Bitmap bitmap) {
        return saveBitmapToSdCard(bitmap, IMAGES_DIR_PATH, null);
    }

    /**
     * 将bitmap保存到本地（默认地址,指定图片名字）
     *
     * @return 图片全路径
     */
    public static String saveBitmapToSdCard(Bitmap bitmap, String fileName) {
        return saveBitmapToSdCard(bitmap, IMAGES_DIR_PATH, fileName);
    }

    /**
     * 将bitmap保存到本地指定路径
     *
     * @return 图片全路径
     */
    public static String saveBitmapToSdCard(Bitmap bitmap, String dirPath, String fileName) {
        String path = dirPath + (fileName == null ? (System.currentTimeMillis() + ".png") : fileName);
        File file = new File(path);
        FileOutputStream fos = null;
        try {
            if (file.exists()) {
                file.delete();
            }
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            //通知图库更新
            MyApplication.myApplication.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(new File(path))));
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showText("保存失败");
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return path;
    }


    /**
     * file复制到指定路径
     */
    public static boolean copyFileTo(File oldFile, String newPath) {
        try {
            if (oldFile.exists()) {
                InputStream inStream = new FileInputStream(oldFile);
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((length = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, length);
                }
                inStream.close();
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * file移动到指定路径
     */
    public static boolean moveFileTo(File oldFile, String newPath) {
        try {
            return oldFile.renameTo(new File(newPath));
        } catch (Exception e) {
            return false;
        }

    }


    /**
     * 在限定的尺寸内读取bitmap
     *
     * @param path
     * @param maxSize
     * @return
     */
    public static Bitmap getBitmapByMaxSize(String path, int maxSize) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        BitmapFactory.decodeFile(path, options);

        //计算缩小倍数
        int outHeight = options.outHeight;
        int outWidth = options.outWidth;
        int inSampleSize = 1;
        //先根据宽度进行缩小  
        while (outWidth / inSampleSize > maxSize) {
            inSampleSize++;
        }
        //然后根据高度进行缩小
        while (outHeight / inSampleSize > maxSize) {
            inSampleSize++;
        }
        options.inSampleSize = inSampleSize;

        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

    static class PathGetter {
        static String getBasePath() {
            String path = Environment.getExternalStorageDirectory() + "/" + MyApplication.myApplication.getPackageName() + "/";
            mkdirs(path);
            return path;
        }

        static String getImagesPath() {
            String path = BASE_PATH + "images/" + MyApplication.myApplication.getPackageName() + "/";
            mkdirs(path);
            return path;
        }

        static String getFilesPath() {
            String path = BASE_PATH + "files/";
            mkdirs(path);
            return path;
        }

        static String getVoicesPath() {
            String path = BASE_PATH + "voices/";
            mkdirs(path);
            return path;
        }

        static String getVideosPath() {
            String path = BASE_PATH + "videos/";
            mkdirs(path);
            return path;
        }


        /**
         * 在文件夹不存在时，创建
         *
         * @param path
         */
        static void mkdirs(String path) {
            try {
                if (!new File(path).exists()) {
                    new File(path).mkdirs();
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 获取文件类型图片
     *
     * @return
     */
    /*public static int getFileTypeImage(String path) {
        int resId = R.drawable.file;
        if (TextUtils.isEmpty(path)) {
            return resId;
        }

        path = path.toLowerCase();

        if (path.endsWith(".apk")) {
            //APK文件格式
            resId = R.drawable.apk;
        } else if (path.endsWith(".txt")) {
            //TXT文件格式
            resId = R.drawable.txt;
        } else if (path.endsWith(".pdf")) {
            //PDF文件格式
            resId = R.drawable.pdf;
        } else if (path.endsWith(".docx") || path.endsWith(".doc") || path.endsWith(".docm")
                || path.endsWith(".dotx") || path.endsWith(".dotm")) {
            //Word文件格式
            resId = R.drawable.word;
        } else if (path.endsWith(".xlsx") || path.endsWith(".xlsm") || path.endsWith(".xltx")
                || path.endsWith(".xltm") || path.endsWith(".xlsb") || path.endsWith(".xlam")) {
            //Excel文件格式
            resId = R.drawable.excel;
        } else if (path.endsWith(".pptx") || path.endsWith(".pptm") || path.endsWith(".ppsx")
                || path.endsWith(".ppsx") || path.endsWith(".potx") || path.endsWith(".potm") || path.endsWith(".ppam")) {
            //PPT文件格式
            resId = R.drawable.ppt;
        }

        return resId;
    }*/

    /**
     * 是否是图片文件
     */
    public static boolean isImageFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }

        path = path.toLowerCase();
        if (path.endsWith(".png") || path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".mbp") || path.endsWith(".gif")
                || path.endsWith(".psd") || path.endsWith(".tiff") || path.endsWith(".tga") || path.endsWith(".eps")) {
            return true;
        }
        return false;
    }


    /**
     * 是否是视频文件
     */
    public static boolean isVideoFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        path = path.toLowerCase();
        if (path.endsWith(".avi") || path.endsWith(".wmv") || path.endsWith(".mpeg") || path.endsWith(".mp4")
                || path.endsWith(".mkv") || path.endsWith(".flv") || path.endsWith(".f4v") || path.endsWith(".m4v")
                || path.endsWith(".rmvb") || path.endsWith(".rm") || path.endsWith(".3gp") || path.endsWith(".dat")
                || path.endsWith(".ts") || path.endsWith(".mts") || path.endsWith(".vob") || path.endsWith(".mov")) {
            return true;
        }
        return false;
    }


    /****
     * 计算文件大小
     *
     * @param length
     * @return
     */
    public static String getFileSize(long length) {
        if (length >= 1048576) {
            return CommonUtil.numFormat(length / 1048576d, "0.##", RoundingMode.HALF_UP) + "MB";
        } else if (length >= 1024) {
            return CommonUtil.numFormat(length / 1024d, "0.##", RoundingMode.HALF_UP) + "KB";
        } else if (length < 1024) {
            return length + "B";
        } else {
            return "0KB";
        }
    }
}
